// 举报相关函数
var constant = require('../../const');
var models = require('../../models');
var AV = require('leanengine');

/*
 * title: 获取举报管理的页面
 */
function getReport(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}
	//0等待处理 1 已经处理 
	var status = req.query.status || 0;
	//type:0:举报 1 投诉
	var type = req.query.type || 0;
	var Report = models.MLReportRecord;

	var query = new AV.Query(Report);
	if (status == 0) {
		query.equalTo("status", 0)
	} else if (status == 1) {
		query.equalTo("status", 1)
	} else if (status == 2) {
		query.equalTo("status", 2)
	}
	if (type == 0) {
		query.notEqualTo("type", 1);
	} else if (type == 1) {
		query.equalTo("type", 1);
	} else if (type == 2) {
		query.equalTo("type", 2);
	}
	query.include("reportee");
	query.include("reporter");
	query.descending("createdAt");
	query.limit(1000);
	query.find({
		success: function(report) {
			var data = {
				"username": req.session.username,
				"report": report
			};
			res.render('admin/report', data);
		},
		error: function(error) {
			res.success(error);
		}
	});
}

/*
 * title: 处理用户举报
 */
function handleReport(req, res) {
	//type 0：警告，type 1: 封号， 2；禁言，3：忽略
	var userId = req.body.userId;
	var reportType = req.body.reportType;
	var reportId = req.body.reportId;
	var content = req.body.content || "";
	if (reportType == 0) {
		// 警告
		var query = new AV.Query(models.MLReportRecord);
		query.get(reportId).then(function(report) {
			report.set('status', constant.REPORT_STATUS_FINISHED);
			report.save(null, {
				success: function(results) {
					// 向发起人发送系统消息
					AV.Cloud.run('sendSysMsg', {
						"touserId": userId,
						"type": 0,
						"msg": content
					}, {
						success: function(result) {
							res.send({
								"code": 0,
								"msg": "发送成功"
							});
						},
						error: function(error) {
							res.send({
								"code": 1,
								"msg": "发送失败"
							});
						}
					});
				},
				error: function(error) {
					res.send({
						"code": 1,
						"msg": "警告失败"
					});
				}
			});
		});
	} else if (reportType == 1) {
		//封号
		var query = new AV.Query(models.MLReportRecord);
		query.include("reportee")
		query.get(reportId).then(function(report) {
			user = report.get("reportee")
			report.set('status', constant.REPORT_STATUS_FINISHED);
			report.save(null, {
				success: function(results) {
					user.set("status", constant.USER_STATUS_DISABLE)
					user.save(null, {
						success: function(user) {
							var tokenQuery = new AV.Query(models.HXToken);
							tokenQuery.descending("createdAt");
							tokenQuery.find({
								success: function(results) {
									var token = results[0].get('token');
									// 发送会话消息
									AV.Cloud.httpRequest({
										method: 'POST',
										url: 'https://a1.easemob.com/xiaocan/' + constant.APP_NAME + '/messages',
										headers: {
											"Content-Type": "application/json",
											"Authorization": "Bearer " + token
										},
										body: {
											"target_type": "users", // users 给用户发消息, chatgroups 给群发消息
											"target": [user.id], // 注意这里需要用数组,数组长度建议不大于20, 即使只有一个用户,   
											// 也要用数组 ['u1'], 给用户发送时数组元素是用户名,给群组发送时  
											// 数组元素是groupid
											"msg": {
												"type": "cmd",
												"action": constant.ACTION_DISABLE_USER
											},
											"from": "MLSYSTEM", //表示这个消息是谁发出来的, 可以没有这个属性, 那么就会显示是admin, 如果有的话, 则会显示是这个用户发出的

										},
										success: function(httpResponse) {
											res.send({
												"code": 0,
												"msg": "封号成功"
											});
										},
										error: function(httpResponse) {
											res.send({
												"code": 1,
												"msg": "封号失败"
											});
										}
									});
								},
								error: function() {
									res.send({
										"code": 1,
										"msg": "封号失败"
									});
								}
							})

						},
						error: function(error) {
							res.send({
								"code": 1,
								"msg": "封号失败"
							});
						}
					})
				},
				error: function(error) {
					res.send({
						"code": 1,
						"msg": "封号失败"
					});
				}
			});
		});
	} else if (reportType == 2) {
		//禁言
		var query = new AV.Query(models.MLReportRecord);
		query.include("reportee")
		query.get(reportId).then(function(report) {
			user = report.get("reportee")
			report.set('status', constant.REPORT_STATUS_FINISHED);
			report.save(null, {
				success: function(results) {
					user.set("status", constant.USER_STATUS_FORBIDDEN)
					user.set("forbiddenTime", new Date())
					user.save(null, {
						success: function(user) {
							var tokenQuery = new AV.Query(models.HXToken);
							tokenQuery.descending("createdAt");
							tokenQuery.find({
								success: function(results) {
									var token = results[0].get('token');
									// 发送会话消息
									AV.Cloud.httpRequest({
										method: 'POST',
										url: 'https://a1.easemob.com/xiaocan/' + constant.APP_NAME + '/messages',
										headers: {
											"Content-Type": "application/json",
											"Authorization": "Bearer " + token
										},
										body: {
											"target_type": "users", // users 给用户发消息, chatgroups 给群发消息
											"target": [user.id], // 注意这里需要用数组,数组长度建议不大于20, 即使只有一个用户,   
											// 也要用数组 ['u1'], 给用户发送时数组元素是用户名,给群组发送时  
											// 数组元素是groupid
											"msg": {
												"type": "cmd",
												"action": constant.ACTION_FORBIDDEN_USER
											},
											"from": "MLSYSTEM", //表示这个消息是谁发出来的, 可以没有这个属性, 那么就会显示是admin, 如果有的话, 则会显示是这个用户发出的

										},
										success: function(httpResponse) {
											AV.Cloud.run('sendSysMsg', {
												"touserId": user.id,
												"type": 4
											}, {
												success: function(result) {
													res.send({
														"code": 0,
														"msg": "发送成功"
													});
												},
												error: function(error) {
													res.send({
														"code": 1,
														"msg": "发送失败"
													});
												}
											});
										},
										error: function(httpResponse) {
											res.send({
												"code": 1,
												"msg": "禁言失败"
											});
										}
									});
								},
								error: function() {
									res.send({
										"code": 1,
										"msg": "禁言失败"
									});
								}
							})

						},
						error: function(error) {
							res.send({
								"code": 1,
								"msg": "禁言失败"
							});
						}
					})
				},
				error: function(error) {
					res.send({
						"code": 1,
						"msg": "封号失败"
					});
				}
			});
		});
	} else {
		//忽略
		var query = new AV.Query(models.MLReportRecord);
		query.get(reportId).then(function(report) {
			report.set('status', constant.REPORT_STATUS_CANCEL);
			report.save(null, {
				success: function(results) {
					res.send({
						"code": 0,
						"msg": "忽略成功"
					});
				},
				error: function(error) {
					res.send({
						"code": 1,
						"msg": "忽略失败"
					});
				}
			});
		});
	}
}

function reportContact(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}
	var userId = req.body.userId;
	var content = req.body.content;
	console.log(content)
	AV.Cloud.run('sendSysMsg', {
		"touserId": userId,
		"type": 0,
		"msg": content
	}, null);
	res.send({
		"code": 0,
		"msg": "发送成功"
	});
}

//取消话题的屏蔽
function cancleScreen(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}
	var circleId = req.body.circleId;
	var query = new AV.Query(models.MLCircle);
	query.get(circleId).then(function(circle) {
		circle.set('status', 0);
		circle.save(null, {
			success: function(results) {
				res.send({
					"code": 0,
					"msg": "成功"
				});
			},
			error: function(error) {
				res.send({
					"code": 1,
					"msg": "失败"
				});
			}
		});
	});
}

//将话题设置永不屏蔽
function neverScreen(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}
	var circleId = req.body.circleId;
	var query = new AV.Query(models.MLCircle);
	query.get(circleId).then(function(circle) {
		circle.set('status', 2);
		circle.save(null, {
			success: function(results) {
				res.send({
					"code": 0,
					"msg": "成功"
				});
			},
			error: function(error) {
				res.send({
					"code": 1,
					"msg": "失败"
				});
			}
		});
	});
}

exports.getReport = getReport;
exports.handleReport = handleReport;
exports.reportContact = reportContact;
exports.cancleScreen = cancleScreen;
exports.neverScreen = neverScreen;